package br.com.extrajudicial.dao;

import java.util.List;

import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.caelum.vraptor.ioc.Component;
import br.com.extrajudicial.models.Cart;
import br.com.extrajudicial.models.ItemOrder;
import br.com.extrajudicial.models.Order;
import br.com.extrajudicial.models.UserSession;

@Component
public class OrderDao extends GenericDao<Order> {
	
	@Autowired private Cart cart;
	@Autowired private ItemOrderDao itemOrderDao;
	@Autowired private UserSession userSession;
	
	@Override
	public void save(Order order) {
		Transaction tx = this.getSession().beginTransaction();
		this.getSession().save(order);
		this.refresh(order);
		for (ItemOrder cartItem : cart.getCartItems()) {
			cartItem.setOrder(order);
			this.itemOrderDao.getSession().save(cartItem);
		}
		tx.commit();
		this.cart.clearCart();
	}
	
	@SuppressWarnings("unchecked")
	public List<Order> listCurrentUserOrders() {
		return this.getSession().createCriteria(Order.class)
			.add(Restrictions.eq("user", this.userSession.getCurrentUser()))
			.addOrder(org.hibernate.criterion.Order.desc("id"))
			.list();
	}

}
